package com.eagle.scali.commoncenter.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 *  Feign传递用户上下文
 *  @author eagle liu
 */
@Slf4j
public class FeignContextInterceptor implements RequestInterceptor {

	@Override
	public void apply(RequestTemplate template) {
		log.info("Enter feign interceptor..");
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
		
		if(attributes != null) {
			HttpServletRequest request = attributes.getRequest();
			String token = request.getHeader("X-Token");
			log.info("The token is {}",token);
	        Enumeration<String> headerNames = request.getHeaderNames();
	        if (headerNames != null) {
	            while (headerNames.hasMoreElements()) {
	                String name = headerNames.nextElement();
	                String values = request.getHeader(name);
	                template.header(name, values);
	            }
	        }
	        log.info("open feign>exchange the token done");
		}

	}

}
